package com.xiaomei.manager.web.controller;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaomei.manager.model.Advertisement;
import com.xiaomei.manager.model.Experience;
import com.xiaomei.manager.service.IAdvertisementService;
import com.xiaomei.manager.utils.Constants;
import com.xiaomei.manager.web.aliyun.OSS.AliyunUpload;
import com.xiaomei.manager.web.dto.req.AdvertQueryDto;
import com.xiaomei.manager.web.page.Page;


@Controller
@RequestMapping("/advert")
public class AdvertController {
	
	@Autowired
	private IAdvertisementService iAdvertisementService;
	private Logger logger = Logger.getLogger(ExperienceController.class);
	
	@RequiresPermissions("advert:view")
	@RequestMapping()
	public String list(Model model,AdvertQueryDto dto,Page<Advertisement>page) throws UnsupportedEncodingException{
		iAdvertisementService.getAdvertForList(dto, page);
		model.addAttribute("dto", dto);
		model.addAttribute("page", page);
		return "advert/list";
	}
	
	/**
     * 添加活动
     * @param model
     * @return
     */
	 @RequiresPermissions("advert:create")
	    @RequestMapping( value = "/create",method = RequestMethod.GET)
	    public String showCreateForm(Model model) {	        
	        model.addAttribute("exp", new Advertisement());
	        model.addAttribute("op", "新增");
	        return "advert/edit";
	    }

    @RequiresPermissions("advert:create")
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public String create(Advertisement exp ,@RequestParam("files") MultipartFile[] files, RedirectAttributes redirectAttributes) {
    
    	//获取活动ID
    	Integer backid = iAdvertisementService.selectMaxID();
    	Integer id = 0;
    	if(backid == null){
    		id = 1;
    	}else{
    		id = backid + 1;
    	}
    	exp.setId(id);
    	 if(files != null && files.length > 0){  
	            //循环获取file数组中得文件  
	    		int i ;
	            for(i = 0;i<files.length;i++){  
	                MultipartFile file = files[i];	                
	                String fileName = file.getOriginalFilename();	                
	                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
		 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
		                String finalFileName = "advert/"+id+"/img_"+(i+1)+extention;
		                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);
		                if(i == 0){
		                	exp.setAdvertImg(url);		                
		                }
		            try{
		                AliyunUpload.getInstance();	                
		                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
		                }catch (Exception e) {
							logger.info("新增广告异常！");
						}	                  
	                }  
	            } 
	    	}
    	//插入体验券 
//    	exp.setTicketAlreadyCount(0);
    	iAdvertisementService.createAdvert(exp);
        redirectAttributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/advert";
    }
    /**
     * 更新广告
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("advert:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Integer id, Model model){
    	 model.addAttribute("exp", iAdvertisementService.findOne(id));
	        model.addAttribute("op", "修改");
	        return "advert/edit";
	   
   }
    @RequiresPermissions("advert:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(Advertisement exp, @RequestParam("files") MultipartFile[] files , @PathVariable("id") Integer id, RedirectAttributes redirectAttributes, HttpServletRequest request){	    		    
    	if(files != null && files.length > 0){  
            //循环获取file数组中得文件  
    		int i ;
            for(i = 0;i<files.length;i++){  
                MultipartFile file = files[i];	                
                String fileName = file.getOriginalFilename();	                
                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
	 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
	                String finalFileName = "advert/"+id+"/img_"+(i+1)+extention;
	                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);	            
	                if(i == 0){
	                	exp.setAdvertImg(url);		                
	                }
	            try{
	                AliyunUpload.getInstance();	                
	                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
	                }catch (Exception e) {
						logger.info("修改广告失败！");
					}	                  
                }  
            } 
    	}
    	//Advertisement backExp = iAdvertisementService.selectExperienceById(id);
    	iAdvertisementService.updateExperience(exp);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/advert";
    }
    /**
     * 删除广告
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("advert:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Integer id, Model model){
    	 model.addAttribute("exp", iAdvertisementService.findOne(id));
	        model.addAttribute("op", "删除");
	        return "advert/edit";
	   
   }
    @RequiresPermissions("advert:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Integer id, RedirectAttributes redirectAttributes) {	       
    	Advertisement exp = iAdvertisementService.selectExperienceById(id);
        if(exp.getAdvertImg()!=null && !exp.getAdvertImg().equals("")){
        	 AliyunUpload.removeOssObject(exp.getAdvertImg());
        }
       iAdvertisementService.deleteExperience(id);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/advert";
    }
    
    @InitBinder   
    public void initBinder(WebDataBinder binder) {   
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   
        dateFormat.setLenient(true);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    }
	
}
